package com.pshcp.common.logaop;

import com.alibaba.fastjson.JSONObject;
import com.framework.logaop.ExternalLog;
import com.framework.thread.ReqComTool;
import com.pshcp.service.ExternalLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Description: TODO
 * @Author: xiaoche
 * @Date: 2023/3/17 15:37
 */
@Slf4j
@Component
@Aspect
public class ExternalLogAspect {

    @Autowired
    private ExternalLogService externalLogService;

    @Around("@annotation(externalLog)")
    public Object doAround(ProceedingJoinPoint pjp, ExternalLog externalLog) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object obj = null;
        try {
            obj = pjp.proceed();
        } finally {
            long endTime = System.currentTimeMillis();
            MethodSignature signature = (MethodSignature) pjp.getSignature();
            String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
            com.pshcp.domain.model.ExternalLog externalLogDO = new com.pshcp.domain.model.ExternalLog();
            externalLogDO.setPshcpTraceId(ReqComTool.getPshcpTraceId());
            externalLogDO.setMethod(methodName);
            externalLogDO.setSpendTime((endTime - startTime));
            externalLogDO.setReqTxt(JSONObject.toJSONString(pjp.getArgs()));
            externalLogDO.setRspTxt(obj != null ? obj.toString() : "");
            externalLogService.insert(externalLogDO);
            log.info("traceId=>{},methodName=>{},req=>{},resp=>{}",
                    externalLogDO.getPshcpTraceId(),
                    methodName,
                    externalLogDO.getReqTxt(),
                    externalLogDO.getRspTxt());
        }
        return obj;
    }
}
